package main

import (
	"context"
	"fmt"
	"gitee.com/jinmingzhi/eth-learn/pkg/ethtool"
	"github.com/ethereum/go-ethereum/accounts/abi"
	"github.com/ethereum/go-ethereum/common"
	"io/ioutil"
	"math/big"
	"strings"
)

var (
	url     = "http://localhost:8545"
	fileDir = "/Users/jinmingzhi/eth-learn/5day/build"
)

func main() {
	abiBytes, err := ioutil.ReadFile(fileDir + "/EzToken.abi")
	assert(err)

	binHexBytes, err := ioutil.ReadFile(fileDir + "/EzToken.bin")
	assert(err)

	binByte := common.Hex2Bytes(string(binHexBytes))

	tokenAbi, err := abi.JSON(strings.NewReader(string(abiBytes)))
	assert(err)

	// 合约构造函数调用参数进行ABI编码
	encodedParams, err := tokenAbi.Pack(
		"",                // 构造函数
		big.NewInt(1000000), // 总量
		"HAPPY COIN",        // 代币名称
		uint8(0),            // 小数点
		"HAPY",              // 代币简称
	)

	assert(err)

	data := append(binByte, encodedParams...)



	client, err := ethtool.Dial(url)
	assert(err)

	ctx := context.Background()

	accounts, err := client.EthAccounts(ctx)
	assert(err)

	// ABI编码后， 部署合约是一个交易，因此 我们需要声明部署账户和gas用量。
	msg := map[string]interface{}{
		"from": accounts[1],               // 该账号拥有所有代币
		"data": common.Bytes2Hex(data),
		"gas":  big.NewInt(2000000),
	}

	txid, err := client.EthSendTransaction(ctx, msg)
	assert(err)
	fmt.Println("txid:", txid)

	receipt, err := client.EthGetTransactionReceipt(ctx, txid)
	assert(err)
	fmt.Println("contract address:", receipt.ContractAddress.Hex())

	err = ioutil.WriteFile(fileDir+"/EzToken.address", []byte(receipt.ContractAddress.Hex()), 0644)
	assert(err)

	fmt.Println("done")
}

func assert(err error) {
	if err != nil {
		panic(err)
	}
}
